package com.dc.kylin.flowable.service;

import com.dc.kylin.flowable.vo.LeaveRequest;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class LeaveService {

    private RuntimeService runtimeService;

    private TaskService taskService;

    private HistoryService historyService;

    private RepositoryService repositoryService;

    // 启动请假流程
    public ProcessInstance startLeaveProcess(LeaveRequest leaveRequest) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("applicant", leaveRequest.getApplicant());
        variables.put("deptLeader", "deptLeader1"); // 实际应用中可以从用户服务获取
        variables.put("hrStaff", "hr1"); // 实际应用中可以从用户服务获取

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "leaveApproval",
                variables
        );

        // 完成第一个任务(填写申请)
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId())
                .singleResult();

        Map<String, Object> taskVariables = new HashMap<>();
        taskVariables.put("leaveType", leaveRequest.getLeaveType());
        taskVariables.put("startDate", leaveRequest.getStartDate());
        taskVariables.put("endDate", leaveRequest.getEndDate());
        taskVariables.put("reason", leaveRequest.getReason());

        taskService.complete(task.getId(), taskVariables);

        return processInstance;
    }

    // 获取用户待办任务
    public List<Task> getUserTasks(String userId) {
        return taskService.createTaskQuery()
                .taskAssignee(userId)
                .list();
    }

    // 部门经理审批
    public void deptLeaderApprove(String taskId, Boolean approved, String comment) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("deptLeaderApproved", approved);
        variables.put("deptLeaderComment", comment);
        taskService.complete(taskId, variables);
    }

    // HR备案
    public void hrRecord(String taskId, String comment) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("hrComment", comment);
        taskService.complete(taskId, variables);
    }

    // 获取请假申请详情
    public LeaveRequest getLeaveRequest(String processInstanceId) {
        LeaveRequest leaveRequest = new LeaveRequest();
        leaveRequest.setProcessInstanceId(processInstanceId);

        // 从历史变量中获取数据
        List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(processInstanceId)
                .list();

        for (HistoricVariableInstance variable : variables) {
            switch (variable.getVariableName()) {
                case "applicant":
                    leaveRequest.setApplicant((String) variable.getValue());
                    break;
                case "leaveType":
                    leaveRequest.setLeaveType((String) variable.getValue());
                    break;
                case "startDate":
                    leaveRequest.setStartDate((Date) variable.getValue());
                    break;
                case "endDate":
                    leaveRequest.setEndDate((Date) variable.getValue());
                    break;
                case "reason":
                    leaveRequest.setReason((String) variable.getValue());
                    break;
                case "deptLeaderApproved":
                    leaveRequest.setDeptLeaderApproved((Boolean) variable.getValue());
                    break;
                case "deptLeaderComment":
                    leaveRequest.setDeptLeaderComment((String) variable.getValue());
                    break;
                case "hrComment":
                    leaveRequest.setHrComment((String) variable.getValue());
                    break;
            }
        }

        // 获取流程状态
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        if (processInstance.getEndTime() != null) {
            leaveRequest.setStatus("已结束");
        } else {
            leaveRequest.setStatus("进行中");
        }

        return leaveRequest;
    }

    // 获取流程图
    public InputStream getProcessDiagram(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());

        List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);

        return new DefaultProcessDiagramGenerator().generateDiagram(
                bpmnModel,
                "png",
                activeActivityIds,
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体",
                null,
                1.0,
                true
        );
    }
}
